package cn.lytcom.architecture.manager;

import android.content.Context;

import cn.lytcom.architecture.MyApplication;
import cn.lytcom.architecture.model.DaoSession;
import cn.lytcom.architecture.model.User;
import cn.lytcom.architecture.model.UserDao;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;
import timber.log.Timber;

/**
 * Created by lytcom on 2017/5/7.
 */

public class DbManager {

    private Context context;

    public DbManager(Context context) {
        this.context = context.getApplicationContext();
        Timber.i("DbManager constructor");
    }

    private DaoSession getDaoSession() {
        return MyApplication.getMyApplication().getDaoSession();
    }

    public User getUser(String name) {
        return getDaoSession().getUserDao()
            .queryBuilder()
            .where(UserDao.Properties.Login.eq(name))
            .build()
            .unique();
    }

    public void setUser(User user) {
        getDaoSession().getUserDao().insertOrReplace(user);
    }

    public Observable<User> getUserByName(final String name) {
        return Observable.create(new ObservableOnSubscribe<User>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<User> e) throws Exception {
                User user = getUser(name);
                if (user != null) {
                    e.onNext(user);
                    Timber.i("getUserByName: " + Thread.currentThread().getName());
                }
                e.onComplete();
            }
        });
    }
}
